package com.service;

import com.alibaba.fastjson.JSON;
import com.pojo.EventTypeEnum;
import com.pojo.WeChatConstants;
import com.pojo.WechatEvent;
import com.utils.WeChatUtil;
import com.utils.XmlUtil;
import lombok.val;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangyan
 * @version $ Id: WechatService.java, v 0.1 2021/11/19 17:14 zhangyan Exp $
 */
@Service
public class WechatService {

    /**
     * 处理消息
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     */
    public void dealMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 判断是否是get请求
        boolean isGet = Objects.equals(request.getMethod(), RequestMethod.GET.name());
        if (isGet) {
            validate(request, response);
            return;
        }
        response.setHeader("content-type", "text/html;charset=UTF-8");
        ServletInputStream inputStream = request.getInputStream();
        WechatEvent event = XmlUtil.toObj(WechatEvent.class, IOUtils.toString(inputStream));

        System.out.println("微信公众号消息" + JSON.toJSONString(event));
        Long returnTime = System.currentTimeMillis();
        String msgEvent = event.getMsgType();
        String appId = request.getParameter("appId");
        String openId = event.getFromUserName();
    }

    /**
     * 验证消息合法性
     *
     * @param request HttpServletRequest
     * @return true-合法;true-非法
     */
    private void validate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        // log.info("微信加密签名: $signature | 时间戳: $timestamp | 随机数: $nonce | 随机字符串:$echostr")
        List<String> list = new ArrayList<String>();
        list.forEach(
                System.out::println
        );
        list.add(timestamp);
        list.add(nonce);
        list.add("token");
        Collections.sort(list);
        String signStr = DigestUtils.sha1Hex(String.join("", list));
        if (signStr.equals(signature)) {
            response.getWriter().write(echostr);
        } else {
            System.out.println("签名不一致");
        }
    }

    /**
     * 处理用户请求
     * @param request
     * @return
     */
    public String processRequest(HttpServletRequest request) {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent;
        try {
            // 调用parseXml方法解析请求消息
            Map<String, String> requestMap = WeChatUtil.parseXml(request);
            // 消息类型
            String msgType = requestMap.get(WeChatConstants.MsgType);
            String mes = "";
            // 事件推送
            if (StringUtils.equals(msgType, WeChatConstants.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType = requestMap.get(WeChatConstants.Event);
                // 关注
                if (StringUtils.equals(eventType, EventTypeEnum.subscribe.name())) {
                    respContent = "欢迎关注【爱比永远多一天】公众号";
                    respXml = WeChatUtil.sendTextMsg(requestMap, respContent);
                }
            }

            if (org.springframework.util.StringUtils.isEmpty(respXml)) {
                mes = "我不知道哦!";
                respXml = WeChatUtil.sendTextMsg(requestMap, mes);
            }
            return respXml;
        } catch (Exception e) {
        }
        return null;
    }
}
